<template>
    <div class="add-first-box">
        <el-button type="success" size="small" title="新增权限组" @click="editAuthority('add')">
            <el-icon size="18"><DocumentAdd /></el-icon>
        </el-button>
        <el-button type="primary" size="small" @click="reSearch">查询</el-button>
    </div>
    <div class="second-box">
        <div class="authirity-box" v-for="(item) in authoritysInfo" :key="item.ID">
            <div class="title-box">{{ item.AUTHORITYNAME }}</div>
            <div class="icon-box">
                <el-button type="warning" size="small" title="编辑权限" @click="editAuthority('selectChange',item)">
                    <el-icon size="18"><BrushFilled /></el-icon>
                </el-button>
                <el-button type="primary" size="small" title="编辑" @click="editAuthority('update',item)">
                    <el-icon size="18"><Edit /></el-icon>
                </el-button>
                <el-button type="danger" size="small" title="删除" @click="editSubmit('delete',item)">
                    <el-icon size="18"><RemoveFilled /></el-icon>
                </el-button>
            </div>            
        </div>
    </div>
    <Drawer ref="drawerRef" :title="title" :size="size"
    @cancel-submit="resetForm"
    @submit="editSubmit(submitType,submitData)"
    >
        <el-form :model="authoritysObj" ref="updateFormRef" :rules="rules" v-if="submitType !== 'selectChange'">
            <el-form-item label="ID" :label-width="formLabelWidth">
                <el-input v-model="authoritysObj.ID" autocomplete="off" disabled />
            </el-form-item>
            <el-form-item label="权限组" :label-width="formLabelWidth" prop="AUTHORITYNAME">
                <el-input v-model="authoritysObj.AUTHORITYNAME" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="备注" :label-width="formLabelWidth" >
                <el-input v-model="authoritysObj.REMARK" autocomplete="off" />
            </el-form-item>
        </el-form>
        <el-tree ref="treeRef" style="max-width: 600px" :data="dirsInfo" v-if="submitType === 'selectChange'"
            node-key="ID" default-expand-all show-checkbox
            :check-strictly="checkStrictly"
            :expand-on-click-node="false"
            @check="handleTreeCheck"
        >
            <template #default="{ node, data }">
                <span class="custom-tree-node">
                    <div class="title-span-box">
                        <div class="icon-title-box">
                            <el-icon size="18">
                                <component :is="data.CUST_TYPE ? 'Folder' : 'Document'"/>
                            </el-icon>
                            <span>{{ data.TITLE }}</span>
                        </div>
                        <div class="control-btn-box">
                            <el-checkbox v-model="data.IS_ADD" label="增" size="small" /> 
                            <el-checkbox v-model="data.IS_UPDATE" label="改" size="small" /> 
                            <el-checkbox v-model="data.IS_DEL" label="删" size="small" /> 
                        </div>                        
                    </div>
                </span>
            </template>
        </el-tree>
    </Drawer>
</template>

<script setup>
import { ref,reactive, watch } from 'vue'
import {getAuthoritysInfo , hasDirsInfo , editAuthorityInfo ,changeAuthority} from '@/utils/adminApi/authority'
import Drawer from '@/components/Drawer.vue'
import {mainStore} from '@/stores/store'
import { getDirsInfo } from '@/utils/adminApi/dirs'
import { recursion } from '@/utils/recursion'
import {msgOpen} from '@/utils/msg'
import { confirm } from '@/utils/confirm'

let useStore = mainStore()

let authoritysInfo = ref([])
let authoritysObj = reactive({
    ID:null,
    AUTHORTIYNAME:"",
    REMARK:""
})

let drawerRef = ref(null)
let title = ref("")
let size = ref("45%")
let formLabelWidth = ref("80")
let submitType = ref('')
let dirsInfo = ref([])
let hasDirIdArr = ref([]) 
let treeRef = ref(null)
let checkStrictly = ref(true) //el-tree在显示复选框的情况下，是否严格的遵循父子不互相关联的做法
let checkedHasDirs = ref([]) //重新勾选后的目录数组
let submitData = reactive({}) //权限编辑后提交对象


//表单验证ref
let updateFormRef = ref(null)
//输入框验证规则
let rules = reactive({
    AUTHORITYNAME: [
        { required: true, message: '请输入权限组名称', trigger: 'blur' },
    ]
})

//重新查询
const reSearch = async ()=>{
    let authoritysInfoRes = await getAuthoritysInfo()
    // console.log(authoritysInfoRes);    
    authoritysInfo.value = authoritysInfoRes.datas.authoritys
}

//重置权限组对象
const resetForm = ()=>{
    authoritysObj = reactive({
        ID:null,
        AUTHORTIYNAME:"",
        REMARK:""
    })
    checkStrictly.value = true
}


/**
 * 编辑权限组
 * @param type 处理类型
 * @param row  行对象
 */
const editAuthority = async (type,row)=>{
    // console.log(type);
    // console.log(row);       
    submitType.value = type
    drawerRef.value.open()
    if(type === "add"){
        title.value = "新增"
        resetForm()
        submitData = authoritysObj
    }else if(type === "update"){
        title.value = "编辑"
        authoritysObj = row
        submitData = authoritysObj
    }else if(type === "selectChange"){
        title.value = "编辑权限明细"
        hasDirIdArr.value = []
        if(!useStore.dirs.length){
            let dirsRes = await getDirsInfo()
            dirsInfo.value = recursion(dirsRes.datas.dirs)
        }else{
            dirsInfo.value = useStore.dirs
        }  
        // console.log(dirsInfo.value)
        let hasDirsRes = await hasDirsInfo(row.ID)    
        // console.log(hasDirsRes);
        hasDirIdArr.value =  hasDirsRes.datas.hasDirs.map((obj) => obj.DIRID)
        // console.log(hasDirIdArr.value); 
        treeRef.value.setCheckedKeys(hasDirIdArr.value)      
    }
}

/**
 * 选择权限
 * @param {Array} e el-tree勾选事件对象
 */
const handleTreeCheck = (...e)=>{
    // console.log(e) 
    checkStrictly.value = false 
    checkedHasDirs.value = [...e[1].checkedKeys,...e[1].halfCheckedKeys]
    // console.log(checkedHasDirs.value);  
    submitData = reactive({
        oldAuth:hasDirIdArr.value,
        newAuth:checkedHasDirs.value
    })  
    // console.log(submitData)    
}

/**
 * 
 * @param {String} type 处理类型
 * @param {Object} data 表单对象,selectChange改变权限时对象属性为数组
 */
const editSubmit = async (type,data)=>{
    // console.log(type);
    // console.log(data);
    // console.log(data.length);
       
    if(type === 'update' || type === 'add'){
        updateFormRef.value.validate(async (valid)=>{
            if(!valid){
                return false
            }else{         
                drawerRef.value.showLoading()
                let newAuthoritys = await editAuthorityInfo(type,data)
                // console.log(newAuthoritys);
                drawerRef.value.hideLoading()
                drawerRef.value.close()
                msgOpen(newAuthoritys.msg,'success') 
                reSearch()
            }
        })
    }else if(type === "delete"){
        let res = await confirm(data.ID)       
        if(res){
            let newAuthoritys = await editAuthorityInfo(type,data)
            // console.log(newAuthoritys);
            msgOpen(newAuthoritys.msg,'success')
            reSearch()
        }
    }else if(type === "selectChange"){
        if(!data.oldAuth){
            msgOpen("未变更权限，无需提交")
        }else{
            drawerRef.value.showLoading()
            let newAuthoritys = await changeAuthority(type,data)
            // console.log(newAuthoritys);
            drawerRef.value.hideLoading()
            drawerRef.value.close()       
            msgOpen(newAuthoritys.msg,'success')
            checkStrictly.value = true 
        }        
    }
}


//渲染DOM前获取数据
// onBeforeMount(()=>{
//     reSearch()
// })

watch([hasDirIdArr],(newTable, oldTable) => {
    // console.log(newTable[0]);
    hasDirIdArr.value = newTable[0]
})
</script>

<style lang="less" scoped>
.add-first-box {
    height: 5%;
    width: 100%;
    border-bottom: #467df5 .0625rem solid;
    padding-left: 1.25rem;
    display: flex;
    justify-content: start;
    align-items: center;
}
.second-box{
    height: 95%;
    width: 100%;
    .authirity-box{
        height: 2.5rem;
        width: 50%;
        display: flex;
        align-items: center;
        .title-box{
            width: 70%;
            font-size: .875rem;
            color: #5e6166;
            padding-left: 1.25rem;
        }
        .icon-box{
            width: 30%;
            display: flex;
            align-items: center;
        }
    }
    .authirity-box:hover{
        background-color: rgba(238, 239, 241, 0.5);
    }
} 

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    .title-span-box{
        width: 100%;
        flex: 1;
        display: flex;
        align-items: center;
        .icon-title-box{
            width: 50%;
            span{
                margin-left: .625rem;
            }
        }
        .contorl-btn-box{
            width: 50%;
            display: flex;
            align-items: center; 
        }
        
    }
}
</style>